//
//  CAICameraOverlayBottomView.m
//  CAIImagePickerControllerKit
//
//  Created by 海参 on 2022/8/2.
//

#import "CAICameraOverlayBottomView.h"
#import <Masonry/Masonry.h>
#import "CAIImagePickerKitTool.h"
#import "CAICameraBottomPreviewPhotosView.h"
#import "CAICameraBottomPreviewPhotoCell.h"

@interface CAICameraOverlayBottomView ()<CAICameraBottomPreviewPhotosViewDelegate>

@property (nonatomic, strong) NSMutableArray <CAIUIImagePickerCameraPhotoModel *>*photoMArray;

/// 预览小图们
@property (nonatomic, strong) CAICameraBottomPreviewPhotosView *previewPhotosView;

@property (nonatomic, strong) UIView *takeButtonContainer;


/// 取消
@property (nonatomic, strong) UIButton *cancelButton;

/// 拍照按钮
@property (nonatomic, strong) UIButton *takeButton;


/// 确认
@property (nonatomic, strong) UIButton *doneButton;

/// 是否是拍照状态
@property (nonatomic, assign) BOOL isCameraing;


@property (nonatomic, assign) NSInteger selectIndexWithPreviewPhotos;

@end

@implementation CAICameraOverlayBottomView

@synthesize imageArray = _imageArray;

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
        [self addLayout];
    }
    return self;
}

- (void)setUI{
    [self addSubview:self.cancelButton];
    [self addSubview:self.takeButtonContainer];
    [self addSubview:self.takeButton];
    [self addSubview:self.doneButton];
    [self.doneButton setTitle:@"使用照片\n确认送达" forState:UIControlStateNormal];
    [self addSubview:self.previewPhotosView];
    self.isCameraing = YES;
}

- (void)addLayout
{
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.mas_right).offset(-LCDScale_iPhone6(12));
        make.width.mas_equalTo(LCDScale_iPhone6(90));
        make.height.mas_equalTo(LCDScale_iPhone6(40));
        make.bottom.mas_equalTo(self.mas_bottom).offset(-[self doneButtonBottomSpaceLayout]);
    }];
    
    CGFloat centerYOffest = -(self.previewPhotosView.picItemLayoutTop-[CAICameraBottomPreviewPhotoCell pointViewTop]-[CAICameraBottomPreviewPhotoCell pointViewSize].height)/2;
    [self.previewPhotosView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(LCDScale_iPhone6(16));
        make.height.mas_equalTo([self.previewPhotosView getTotalHeightWithRows:1]);
        make.centerY.mas_equalTo(self.doneButton.mas_centerY).offset(centerYOffest);
        make.right.mas_equalTo(self.doneButton.mas_left).offset(-LCDScale_iPhone6(38));
    }];
    
    
    [self.takeButtonContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(LCDScale_iPhone6(73), LCDScale_iPhone6(73)));
        make.bottom.mas_equalTo(self.previewPhotosView.mas_top).offset(-[CAICameraOverlayBottomView takeButtonContainerBottomLayout]);
    }];
    
    [self.takeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.cancelButton.mas_centerY);
        make.centerX.mas_equalTo(self.mas_centerX);
//        make.size.mas_equalTo(CGSizeMake(LCDScale_iPhone6(50), LCDScale_iPhone6(50)));
    }];

    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(LCDScale_iPhone6(25));
        make.height.mas_equalTo(BottomViewScaleHeight(40));
        make.width.mas_equalTo(LCDScale_iPhone6(40));
        make.centerY.mas_equalTo(self.takeButtonContainer.mas_centerY);
    }];
    

}


- (void)layoutSubviews{
    [super layoutSubviews];
    self.doneButton.layer.cornerRadius = CGRectGetHeight(self.doneButton.frame)/2;
    self.takeButtonContainer.layer.cornerRadius = CGRectGetHeight(self.takeButtonContainer.frame)/2;
    self.takeButton.layer.cornerRadius =  CGRectGetHeight(self.takeButton.frame)/2;
}


#pragma mark - 实例方法

- (void)takePictureWithAddPhoto:(nullable CAICameraPhotoInfoModel *)photoModel{
    if (photoModel) {
        ///限制快速拍照情况下，到达最大值后，后续的不要
        if (self.photoMArray.count >= self.maxItemCount && self.maxItemCount>0) {
            return;
        }
        CAIUIImagePickerCameraPhotoModel *model = [CAIUIImagePickerCameraPhotoModel new];
        model.dateTime = photoModel.dateTime;
        model.location = photoModel.location;
        model.photo = photoModel.photo;
        model.photoId = photoModel.photoId;
        if (self.maxItemCount == 1) {
            model.selected = YES;
            [self.photoMArray addObject:model];
            [self switchToPhotoPreviewUI];
        }else{
            model.selected = NO;
            [self.photoMArray addObject:model];
            [self changePhotosWithReloadUI];
        }
        [self.previewPhotosView setData:self.photoMArray];
        [self.previewPhotosView scrollToItemAtIndex:self.photoMArray.count-1];
    }
}

- (void)setImageArray:(NSArray *)imageArray{
    if (_imageArray != imageArray) {
        _imageArray = imageArray;
        [self.photoMArray removeAllObjects];
        if (imageArray.count > self.maxItemCount && self.maxItemCount >0)
        {
            NSRange range = NSMakeRange(0, self.maxItemCount);
            NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
            imageArray = [NSMutableArray arrayWithArray:[imageArray objectsAtIndexes:set]];
        };
        __weak __typeof(&*self)weakSelf = self;
        if (self.maxItemCount == 1) {
            [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CAIUIImagePickerCameraPhotoModel *model = [CAIUIImagePickerCameraPhotoModel new];
                model.photo = obj;
                model.selected = YES;
                [weakSelf.photoMArray addObject:model];
            }];
            [self switchToPhotoPreviewUI];
        }else{
            [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CAIUIImagePickerCameraPhotoModel *model = [CAIUIImagePickerCameraPhotoModel new];
                model.photo = obj;
                model.selected = NO;
                [weakSelf.photoMArray addObject:model];
            }];
            [self changePhotosWithReloadUI];
        }
        [self.previewPhotosView setData:self.photoMArray];
        [self.previewPhotosView scrollToItemAtIndex:self.photoMArray.count-1];
    }
}

- (void)selectPreviewPhotosViewItemAtIndex:(NSInteger)index{
    [self.previewPhotosView selectItemAtIndex:index];
}

- (NSInteger)indexForPreviewPhotosViewSelect{
    return self.selectIndexWithPreviewPhotos;
}


- (void)backToCamera{
    [self switchToCameraUI];
}


#pragma mark - 类方法

+ (CGFloat)takeButtonContainerBottomLayout{
    CGFloat layout = [UIScreen mainScreen].bounds.size.height >=812 ? LCDScale_iPhone6(26):5;
    return layout;
}

- (CGFloat)doneButtonBottomSpaceLayout{
    CGFloat layout = [UIScreen mainScreen].bounds.size.height >=812 ? LCDScale_iPhone6(62):20;
    return layout;
}


+ (CGFloat)bottomViewHeight{
    return [UIScreen mainScreen].bounds.size.height-LCDScale_iPhone6(500.0);
}

+ (CGFloat)bottomViewScaleHeight:(CGFloat)height{
    if ([UIScreen mainScreen].bounds.size.height<812) {
        return (height*[UIScreen mainScreen].bounds.size.height)/812;
    }
    return LCDScale_iPhone6(height);
}



- (void)setCommonTintColor:(UIColor *)commonTintColor{
    if (_commonTintColor != commonTintColor) {
        _commonTintColor = commonTintColor;
        if (commonTintColor) {
            self.doneButton.layer.backgroundColor = commonTintColor.CGColor;
            self.previewPhotosView.pointColor = commonTintColor;
        }
    }
}

#pragma mark - Action

- (void)doneButtonAction:(id)sender{
    if (self.didPickImagesBlock && self.photoMArray.count>0) {
        NSMutableArray *mArray = [self getPhotos];
        self.didPickImagesBlock([mArray copy],[self.photoMArray copy]);
    }
}


- (void)cancelButtonAction:(id)sender{
    if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomViewDidCancel:)]) {
        [self.delegate cameraOverlayBottomViewDidCancel:self];
    }
}

- (void)takeButtonAction:(UIButton *)sender{
    ///如果是预览按钮
    if (!self.isCameraing) {
        [self switchToCameraUI];
    }
    ///如果是拍照按钮
    else{
        ///超过限制：不允许调用拍照
        if (self.photoMArray.count >= self.maxItemCount && self.maxItemCount >0)
        {
            if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomViewDidTakeLimitNumberNotAllow:)]) {
                [self.delegate cameraOverlayBottomViewDidTakeLimitNumberNotAllow:self];
            }
            return;
        };
        
        if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomViewDidTake:)]) {
            [self.delegate cameraOverlayBottomViewDidTake:self];
        }
    }
}



#pragma mark - CAICameraBottomPreviewPhotosViewDelegate

- (void)cameraBottomPreviewPhotosView:(CAICameraBottomPreviewPhotosView *)view commitEditingForRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.photoMArray removeObjectAtIndex:indexPath.item];
    if (!self.isCameraing) {
        if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomView:commitDeleteForRowAtIndexPath:)]) {
            [self.delegate cameraOverlayBottomView:self commitDeleteForRowAtIndexPath:indexPath];
        }
    }
    if (self.photoMArray.count == 0) {
        [self changePhotosWithReloadUI];
        ///如果不是拍照，则变回拍照
        if (!self.isCameraing) {
            self.isCameraing = YES;
            [self.takeButton setImage:nil forState:UIControlStateNormal];
            [self.takeButton setTitle:nil forState:UIControlStateNormal];
            if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomViewDidSwitchPreviewToTakePhoto:)]) {
                [self.delegate cameraOverlayBottomViewDidSwitchPreviewToTakePhoto:self];
            }
        }
    }
}

- (void)cameraBottomPreviewPhotosView:(CAICameraBottomPreviewPhotosView *)view didSelectPicItemAtIndex:(NSInteger)index photos:(NSArray<CAIUIImagePickerCameraPhotoModel *> *)photos{
    if (self.maxItemCount == 1) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomView:didSelectItemAtIndex:)]) {
        [self.delegate cameraOverlayBottomView:self didSelectItemAtIndex:index];
    }
    self.selectIndexWithPreviewPhotos = index;
    [self switchToPhotoPreviewUI];
}


#pragma mark - 其他方法


- (NSMutableArray *)getPhotos{
    
    NSMutableArray *mArray = [NSMutableArray array];
    [self.photoMArray enumerateObjectsUsingBlock:^(CAIUIImagePickerCameraPhotoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mArray addObject:obj.photo];
    }];
    return mArray;
}


#pragma mark - 切换拍照和预览

/// 预览切换||重拍切换
- (void)switchToCameraUI{
    if (self.isCameraing) {
        return;
    }
    self.isCameraing = YES;
    [self.takeButton setImage:nil forState:UIControlStateNormal];
    [self.takeButton setTitle:nil forState:UIControlStateNormal];
    //重拍
    if (self.maxItemCount == 1) {
        [self.photoMArray removeAllObjects];
    }
    //拍摄 
    else{
        [self cleanSelect];
    }
    [self changePhotosWithReloadUI];

    if ([self.delegate respondsToSelector:@selector(cameraOverlayBottomViewDidSwitchPreviewToTakePhoto:)]) {
        [self.delegate cameraOverlayBottomViewDidSwitchPreviewToTakePhoto:self];
    }
}

- (void)switchToPhotoPreviewUI{
    self.isCameraing = NO;
    if (self.maxItemCount == 1) {
        [self switchToOnePhotoPreviewUI];
    }else{
        [self switchToMultiPhotoPreviewUI];
    }
}
- (void)switchToMultiPhotoPreviewUI{
    [self.takeButton setImage:[CAIImagePickerKitTool imageNamed:@"camera_icon"] forState:UIControlStateNormal];
    [self.takeButton setTitle:nil forState:UIControlStateNormal];
}

- (void)switchToOnePhotoPreviewUI{
    [self.takeButton setTitle:@"重拍" forState:UIControlStateNormal];
    [self.takeButton setImage:nil forState:UIControlStateNormal];
    
    [self changePhotosWithReloadUI];
}



///取消选中状态
- (void)cleanSelect{
    if (self.photoMArray.count == 0) {
        return;
    }
    [self.photoMArray enumerateObjectsUsingBlock:^(CAIUIImagePickerCameraPhotoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected = NO;
    }];
    [self.previewPhotosView setData:self.photoMArray];
}

- (void)changePhotosWithReloadUI{
    if (self.photoMArray.count >0) {
        self.cancelButton.hidden = YES;
        self.doneButton.hidden = !self.cancelButton.hidden;
        self.previewPhotosView.hidden = self.doneButton.hidden;

    }else{
        self.cancelButton.hidden = NO;
        self.doneButton.hidden = !self.cancelButton.hidden;
        self.previewPhotosView.hidden = self.doneButton.hidden;
    }
}

#pragma mark - Getter


- (NSMutableArray *)photoMArray{
    if (!_photoMArray) {
        _photoMArray = [NSMutableArray array];
    }
    return _photoMArray;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:LCDScale_iPhone6(16) weight:UIFontWeightMedium];
        [btn addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton = btn;
    }
    return _cancelButton;
}

- (UIButton *)takeButton
{
    if (!_takeButton) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:[UIColor colorWithRed:48/255.0 green:125/255.0 blue:244/255.0 alpha:1.0] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:LCDScale_iPhone6(14) weight:UIFontWeightMedium];
        [btn addTarget:self action:@selector(takeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _takeButton = btn;
    }
    return _takeButton;
}


- (UIButton *)doneButton
{
    if (!_doneButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.backgroundColor = [UIColor colorWithRed:48/255.0 green:125/255.0 blue:244/255.0 alpha:1.0].CGColor;;
        [btn setTitle:@"确认" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:LCDScale_iPhone6(13) weight:UIFontWeightMedium];
        btn.titleLabel.numberOfLines = 0;
        btn.hidden = YES;
        [btn addTarget:self action:@selector(doneButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _doneButton = btn;
    }
    return _doneButton;
}

- (UIView *)takeButtonContainer{
    if (!_takeButtonContainer) {
        UIView *view = [UIView new];
        view.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.24].CGColor;
        _takeButtonContainer = view;
    }
    return _takeButtonContainer;
}

- (CAICameraBottomPreviewPhotosView *)previewPhotosView{
    if (!_previewPhotosView) {
        CAICameraBottomPreviewPhotosView *view = [CAICameraBottomPreviewPhotosView new];
        view.hidden = YES;
        view.picItemWidth = [CAICameraOverlayBottomView bottomViewScaleHeight:58];
        view.picItemHeight = view.picItemWidth;
        view.picItemLayoutTop = LCDScale_iPhone6(9);
        view.picItemLayoutRight = LCDScale_iPhone6(9);
        view.minimumLineSpacing = LCDScale_iPhone6(6);
        view.minimumInteritemSpacing = 0;
        view.delegate = self;
        view.backgroundColor = [UIColor blackColor];
        _previewPhotosView = view;
    }
    return _previewPhotosView;
}


- (NSArray *)imageArray{
    return [[self getPhotos]copy];
}


@end
